package handlers

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"perm/cache"
	"perm/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var users []models.Users
	redis_list_page_key := "list_page_" + strconv.Itoa(page)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_list_page_key).Result()
	if cacheJson == "" {
		fmt.Println("111")
		models.DB.Offset(offset).Limit(size).Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_list_page_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheJson), &users)
	}
	var total int64
	models.DB.Model(&models.Users{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"data":  users,
		"total": total,
		"msg":   "查询成功",
	})
	return
}
